(* This file is part of IsoType.
 *
 * IsoType is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * IsoType is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with IsoType.  If not, see <http://www.gnu.org/licenses/>.
 *)

open OptionMonad

let rec parts eq =
  function
      [] -> []
    | x :: xs ->
	let (p, xs) = List.partition (eq x) xs in
	  (x :: p) :: parts eq xs

let rec add_eq eq x =
  function
      [] -> [x]
    | (y :: _) as ys when eq x y -> ys
    | (y :: ys) -> y :: add_eq eq x ys

let union_eq eq xs ys =
  List.fold_left (fun ys' x -> add_eq eq x ys') ys xs

let rec assoc_eq eq k =
  function
      [] -> raise Not_found
    | ((k', v) :: _) when eq k k' -> v
    | (_ :: l) -> assoc_eq eq k l

let assoc_eq_default v eq k l =
  try
    assoc_eq eq k l
  with
      Not_found -> v

let rec remove_opt_eq eq x =
  function
      [] -> None
    | y :: ys when eq x y -> Some ys
    | y :: ys -> 
	begin
	  match remove_opt_eq eq x ys with
	      None -> None
	    | Some ys' -> Some (y :: ys')
	end

let rec ordered_eq eq xs ys =
  match xs, ys with
      [], [] -> true
    | [], _
    | _, [] -> false
    | x :: xs', y :: ys' -> eq x y && ordered_eq eq xs' ys'

let unordered_eq eq =
  let rec aux xs =
    function
	[] -> xs = []
      | (y :: ys) ->
	  begin
	    match remove_opt_eq eq y xs with
		None -> false
	      | Some xs' -> aux xs' ys
	  end
  in
    aux

let rec remove_opt_unify unify x ys subst =
  match ys with
      [] -> None
    | y :: ys' ->
	begin
	  match unify x y subst with
	      Some subst' -> Some (subst', ys')
	    | None ->
		remove_opt_unify unify x ys' subst
		>>= fun (subst', ys'') -> Some (subst', y :: ys'')
	end

let rec ordered_unify unify xs ys subst =
  match xs, ys with
      [], [] -> Some subst
    | [], _
    | _, [] -> None
    | x :: xs', y :: ys' ->
	unify x y subst
	>>= ordered_unify unify xs' ys'

let unordered_unify unify =
  let rec aux xs ys subst =
    match xs, ys with
	[], [] -> Some subst
      | [], _
      | _, [] -> None
      | _, y :: ys ->
	  remove_opt_unify unify y xs subst
	  >>= fun (subst', xs') -> aux xs' ys subst'
  in
    aux
